package com.ericreboisson.client;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.event.logical.shared.OpenHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class TreeExample implements EntryPoint {
	private final com.ericreboisson.client.Tree<String> rootTree = new com.ericreboisson.client.Tree<String>("");

	public void onModuleLoad() {

		TimeWatch watch = TimeWatch.start();

		ScrollPanel scrollPanel = new ScrollPanel();
		scrollPanel.setHeight("500px");
		scrollPanel.setWidth("200px");

		// scrollPanel.add(createTree());
		scrollPanel.add(createDynamicTree(2));

		Window.alert("Tree creation (ms): " + watch.time());
		// Add it to the root panel.
		RootPanel.get().add(scrollPanel);
	}

	/**
	 * Create static tree
	 * 
	 * @return
	 */
	private Tree createTree() {
		Tree tree = new Tree();
		for (int i = 0; i < 600; i++) {
			TreeItem item = new TreeItem("Item" + i);
			item.addTextItem("");
			// TreeItem subItem = new TreeItem("SubItem" + i);
			// TreeItem innerItem = new TreeItem("InnerItem" + i);
			// subItem.addItem(innerItem);
			// item.addItem(subItem);
			//
			// innerItem.setUserObject(new SampleDto("property1." + i,
			// "property2." + i, "property3." + i));
			tree.addItem(item);

		}
		return tree;
	}

	/**
	 * Get a list of sample DTOs
	 * 
	 * @return
	 */
	public List<SampleDto> getDtoList() {
		List<SampleDto> list = new ArrayList<SampleDto>();
		for (int i = 0; i < 10; i++) {
			list.add(new SampleDto("property1." + i, "property2." + i, "property3." + i));
			list.add(new SampleDto("property1." + i, "property2." + i, "property4." + i));
			list.add(new SampleDto("property1." + i, "property3." + i, "property3." + i));
			list.add(new SampleDto("property1." + i, "property3." + i, "property4." + i));
		}
		return list;
	}

	// public static String createPath(SampleDto dto) {
	// StringBuilder builder = new StringBuilder();
	// builder.append(dto.getProperty1()).append(SEPARATOR).append(dto.getProperty2()).append(SEPARATOR).append(dto.getProperty3());
	// return builder.toString();
	// }

	/**
	 * Create a dynamic tree that will add a random number of children to each
	 * node as it is clicked.
	 * 
	 * @return the new tree
	 */
	private Tree createDynamicTree(int levelToExpand) {
		Tree dynamicTree = new Tree();

		createTreeRepresentation(getDtoList());

		showFirstLevel(dynamicTree);

		dynamicTree.addOpenHandler(new OpenHandler<TreeItem>() {
			@Override
			public void onOpen(OpenEvent<TreeItem> event) {
				TreeItem item = event.getTarget();

				if (item.getChildCount() == 1) {
					// Close the item immediately
					item.setState(false, false);

					// Search for the childs
					String itemText = item.getText();
					com.ericreboisson.client.Tree<String> foundTree = rootTree.recursiveSearch(itemText);

					for (com.ericreboisson.client.Tree<String> tree : foundTree.getChildren()) {
						TreeItem child = item.addTextItem(tree.getData());

						com.ericreboisson.client.Tree<String> leafTree = rootTree.recursiveSearch(child.getText());
						if (leafTree.getChildren().size() == 0) {
							child.setUserObject(leafTree.getUserObject());
						} else {
							child.addTextItem("");

						}

					}

					// Remove the temporary item when we finish loading
					item.getChild(0).remove();

					// Reopen the item
					item.setState(true, false);
				}
			}
		});

		dynamicTree.addSelectionHandler(new SelectionHandler<TreeItem>() {

			@Override
			public void onSelection(SelectionEvent<TreeItem> event) {
				TreeItem item = event.getSelectedItem();
				if (item.getUserObject() != null) {
					Window.alert("Found: " + ((SampleDto) item.getUserObject()).toString());
				}

			}
		});

		expandToLevel(dynamicTree, levelToExpand);

		return dynamicTree;
	}

	private void expandToLevel(Tree dynamicTree, int levelToExpand) {

		for (int i = 0; i < dynamicTree.getItemCount(); i++) {

			TreeItem item = dynamicTree.getItem(i);

			if (levelToExpand > 1) {
				item.setState(true);
			}

			recursiveExpand(levelToExpand, item);

		}
	}

	private void recursiveExpand(int levelToExpand, TreeItem item) {

		if (item.getChildCount() == 0)
			return;
		for (int j = 0; j < item.getChildCount(); j++) {
			if (getLevel(item.getChild(j)) < levelToExpand) {
				item.getChild(j).setState(true);
			}
			;
			recursiveExpand(levelToExpand, item.getChild(j));

		}

	}

	private int getLevel(TreeItem child) {
		int level = 1;
		if (child.getParentItem() == null) {
			return 1;
		} else {
			return 1 + getLevel(child.getParentItem());
		}

	}

	private void showFirstLevel(Tree dynamicTree) {
		for (com.ericreboisson.client.Tree<String> tree : rootTree.getChildren()) {
			TreeItem item = dynamicTree.addTextItem(tree.getData());
			// Temporarily add an item so we can expand this node
			item.addTextItem("");
		}
	}

	private void createTreeRepresentation(List<SampleDto> dtos) {

		// Collections.sort(dtos);

		com.ericreboisson.client.Tree<String> current = rootTree;

		for (SampleDto sampleDto : dtos) {
			com.ericreboisson.client.Tree<String> root = current;

			current = current.child(sampleDto.getProperty1());
			current = current.child(sampleDto.getProperty2());
			current = current.child(sampleDto.getProperty3());

			current.setUserObject(sampleDto);

			current = root;
		}

	}
	
	public static void main(String[] args) {
		TreeExample example = new TreeExample();
		example.createTreeRepresentation(example.getDtoList());
		com.ericreboisson.client.Tree<String> result = example.rootTree.recursiveSearch("property4.7");
		String path = com.ericreboisson.client.Tree.join(result.getPath(),"/");
		System.out.println(path);
	}

}
